<?php

namespace App\Http\Controllers\wechat\notice;

use App\Http\Controllers\Controller;
use App\Models\news\NewsListModel;
use App\Models\news\NewsTemplateModel;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use lxs\api\ApiResponse;

class NewsController extends Controller
{

    /**
     * 获取新闻列表
     */
    public function getNewsList(Request $request): JsonResponse
    {
        $uid = $request->uid;
        $page = $request->input('page');
        $pageSize = $request->input('page_size');

        $model = NewsListModel::select('news_list.id as news_id', 'news_list.is_browse', 'news_list.deleted_at', 'news_template.*')
            ->rightJoin('news_template', function ($join) use ($uid) {
                $join->on('news_list.news_id', '=', 'news_template.id');
            })
            ->where('news_list.uid', '=', $uid)
            ->where('news_list.deleted_at', 0);

        $count = $model->count();

        $list = $model->orderBy('news_template.send_time', 'desc')
                ->offset(($page - 1) * $pageSize)
                ->limit($pageSize)
                ->get()->toArray();
        foreach ($list as $k => $v) {
            $list[$k]['class_name'] = NewsTemplateModel::getClassValues($v['class_type']);
        }

        return ApiResponse::success('获取新闻列表成功', ['list' => $list, 'total' => $count]);
    }


    /**
     * 删除新闻列表
     */
    public function deleteNews(Request $request): JsonResponse
    {
        $id = $request->input('id');
        $uid = $request->uid;
        $list = NewsListModel::where('news_id', $id)->where('uid', $uid)->first();
        if ($list) {
            $list->deleted_at = time();
            $list->save();
            return ApiResponse::success('删除成功');
        }
        return ApiResponse::error('删除失败');
    }


    /**
     * 获取新闻详情
     */
    public function getNewsDetail(Request $request): JsonResponse
    {
        $uid = $request->uid;
        $news_id = $request->input('news_id');
        $list = NewsListModel::with(['getNewsTemplate'])
            ->where('id', $news_id)
            ->where('uid', $uid)
            ->where('deleted_at', 0)
            ->first();
        if ($list) {
            if ($list->is_browse == 0) {
                $list->is_browse = 1;
                $list->save();
            }
            $list->getNewsTemplate->content = explode(',', $list->getNewsTemplate->content);
            return ApiResponse::apiResponseData(200, '获取新闻详情成功', [
                'list' => $list,
            ]);
        }
        return ApiResponse::error('获取新闻详情失败');
    }

}
